package org.example.topicdata;

import org.example.ConnectDatabase;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ChangeTopics extends ConnectDatabase {

    int isOK = 1;
    public Topic dealData(String s){
        String[] data = s.substring(2).split("##");
        Topic topic = new Topic();
        String SQL ="select * from Topics where TID = " + Integer.parseInt(data[0]);
        try {
            Statement sta = con.createStatement();
            ResultSet rs = sta.executeQuery(SQL);
            //获取原始数据
            if (rs.next()) {
                topic.setID(rs.getInt(1));
                topic.setTopicName(rs.getString(2).trim());
                topic.setSelect_A(rs.getString(3).trim());
                topic.setSelect_B(rs.getString(4).trim());
                topic.setSelect_C(rs.getString(5).trim());
                topic.setSelect_D(rs.getString(6).trim());
                topic.setAns(rs.getString(7));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        for (int i = 0; i < data.length; i++) {
            if (data[i].equals("")) continue;
            switch (i){
                case 1:
                    topic.setTopicName(data[i]);
                    break;
                case 2:
                    topic.setSelect_A(data[i]);
                    break;
                case 3:
                    topic.setSelect_B(data[i]);
                    break;
                case 4:
                    topic.setSelect_C(data[i]);
                    break;
                case 5:
                    topic.setSelect_D(data[i]);
                    break;
                case 6:
                    topic.setAns(data[i]);
                    break;
            }
        }
        return topic;
    }

    public int change(Topic topic) {
        new ConnectDatabase();
        try {
            String SQL = "update topics set PROBLEM = '" + topic.topicName + "',ANSWERA = '" + topic.Select_A + "'" +
                    ",ANSWERB = '" + topic.Select_B + "',ANSWERC = '" + topic.Select_C + "',ANSWERD = '" + topic.Select_D +
                    "',ANSWER = '" + topic.ans + "'"+" where TID = " + topic.ID;
            PreparedStatement statement = con.prepareStatement(SQL);
            isOK = statement.executeUpdate();
            con.close();
        } catch (SQLException e) {
            isOK = 0;                //Topics表中ID字段是主键，即不允许ID重复
        }
        return isOK;
    }
}
